package com.harassment.interception.ui.fragments;

import android.app.Activity;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import java.util.HashSet;
import java.util.Set;

public class HIFragmentManager {
    private static final String TAG = "HIFragmentManager";
    private AppCompatActivity mActivity;
    private FragmentManager mSupportFragmentManager;
    private Set<Fragment> mSupportFragments;

    public HIFragmentManager(@NonNull AppCompatActivity activity) {
        mActivity = activity;
        mSupportFragmentManager = activity.getSupportFragmentManager();
        mSupportFragments = new HashSet<>();
    }

    public HIFragmentManager(@NonNull FragmentManager fragmentManager) {
        mSupportFragmentManager = fragmentManager;
        mSupportFragments = new HashSet<>();
    }

    public void replaceFragment(@IdRes int targetLayout, @NonNull Fragment fragment) {
        FragmentTransaction fragmentTransaction = mSupportFragmentManager.beginTransaction();
        fragmentTransaction.replace(targetLayout, fragment);
        fragmentTransaction.commit();
    }

    public void showFragment(@IdRes int targetLayout, @NonNull Fragment fragment) {
        if (!mSupportFragments.contains(fragment)) {
            Log.d(TAG, "showFragment: 没有此fragment");
            addFragment(targetLayout, fragment);
        }
        Log.d(TAG, "showFragment: 数量="+mSupportFragments.size());
        FragmentTransaction fragmentTransaction = mSupportFragmentManager.beginTransaction();
        for (Fragment temp : mSupportFragments) {
            if (temp != fragment) {
                fragmentTransaction.hide(temp);
            }
        }
        fragmentTransaction.show(fragment);
        fragmentTransaction.commitNow();
    }

    public void addFragment(@IdRes int targetLayout, @NonNull Fragment... fragments) {
        Log.d(TAG, "addFragment: 数量="+fragments.length);
        FragmentTransaction fragmentTransaction = mSupportFragmentManager.beginTransaction();
        for (Fragment temp : fragments) {
            mSupportFragments.add(temp);
            fragmentTransaction.add(targetLayout, temp);
        }
        fragmentTransaction.commit();
    }

    public FragmentManager getSupportFragmentManager() {
        return mSupportFragmentManager;
    }
}
